import aiohttp


async def get_news(size=10):
    """
    Sanic是一个异步框架，为了更好的发挥它的性能，有些操作最好也要用异步的
    比如这里发起请求就必须要用异步请求框架aiohttp
    所以使用本服务的时候请先执行: pip install aiohttp
    数据使用的是readhub网站的api接口
    为了使这个数据获取函数正常运行，我会保持更新，所以具体代码见 examples/demo01/news.py
    """
    all_news, readhub_api = [], "https://api.readhub.me/topic"
    try:
        async with aiohttp.ClientSession() as client:
            headers = {'content-type': 'application/json'}
            params = {'pageSize': size}
            async with client.get(readhub_api, params=params, headers=headers) as response:
                assert response.status == 200
                result = await response.json()

            for value in result.get('data', []):
                each_data = {}
                each_data['title'] = value.get('title')
                each_data['summary'] = value.get('summary')
                each_data['news_info'] = value.get('newsArray')
                each_data['updated_at'] = value.get('updatedAt')
                all_news.append(each_data)
            return all_news
    except Exception as e:
        return all_news
